<?php
namespace App\Admin\Controllers\Warehousing;

use App\Admin\Ajax\Warehousing\ReceiveAjax;
use App\Exporter\Warehousing\ReceiveExporter;
use App\Models\Inventory\StorageDetail;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Sys\Logs;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use App\Models\Basics\Supplier;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Maatwebsite\Excel\Facades\Excel;
class ReceiveController extends AdminController{

    protected $title = '采购收货';

    protected function grid()
    {
        $grid = new Grid(new PurchaseOrder());
        $grid->model()->newQuery()
            ->where('status',PurchaseOrder::STATUS_YES) //已下单
            ->orderBy('id', 'ASC');
        $grid->column('purchase_no','订单号');
        $grid->column('pu_user_id','采购人')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('supplier.name','供应商');
        $grid->column('received_status','收货状态')->display(function ($value){
            return PurchaseOrder::$_receivedStatus[$value];
        });
        $grid->column('remarks','备注')->style('max-width:200px');
        $grid->column('order_at','下单时间');
        $grid->column('操作')->view('warehousing.receive.action');
        $grid->disableCreateButton();
        $grid->disableActions();
        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->equal('purchase_no','订单号');
                $filter->equal('supplier_id','供应商')->select(Supplier::options());
                $filter->where(function ($query) {
                    $query->whereHas('order_detail.sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU')->placeholder('模糊查询SKU，名称');
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('received_status','收货状态')->select(PurchaseOrder::$_receivedStatus);
                $filter->between('order_at', '下单日期')->date();
            });
        });
        return $grid;
    }

    /**
     * 明细详情
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function detail($id)
    {
        $purchase = PurchaseOrder::query()->findOrFail($id);
        $orderNum = 0;
        $orderAmount = 0;
        foreach ($purchase->order_detail as $detail){
            $orderNum += $detail->order_num;
            $orderAmount += $detail->order_num * $detail->supplier_price;
        }
        $logs = Logs::getLogs('purchase',$id);

        //国内库存,收货入库记录
        $sDetail = StorageDetail::query()->where('order_no',$purchase->purchase_no)->get()->sortBy('psku_id');
        return view('warehousing.receive-detail.index', compact('id','purchase','logs','sDetail','orderNum','orderAmount'));
    }

    /**
     * 采购收货
     * @param $id
     * @param Content $content
     * @return Content
     */
    protected function confirm($id, Content $content)
    {
        $purchase = PurchaseOrder::query()->findOrFail($id);
        $tax = Supplier::query()->where('id',$purchase->supplier_id)->value('tax'); //税点（默认为0，不含税）
        return $content
            ->title($this->title())
            ->description('收货')
            ->body(view('warehousing.receive-confirm.index', compact('id','purchase','tax')));
    }

    /**
     * 采购出库
     * @param $id
     * @param Content $content
     * @return Content
     */
    protected function outStock($id, Content $content)
    {
        $purchase = PurchaseOrder::query()->findOrFail($id);
        $tax = Supplier::query()->where('id',$purchase->supplier_id)->value('tax'); //税点（默认为0，不含税）
        return $content
            ->title($this->title())
            ->description('出库')
            ->body(view('warehousing.receive-out-stock.index', compact('id','purchase','tax')));
    }

    /**
     * 下载采购单
     * @param $id
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    protected function download($id){
        $purchase = PurchaseOrder::query()->findOrFail($id);
        return Excel::download(new ReceiveExporter($purchase),$purchase->purchase_no.'.xlsx');
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ReceiveAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
}
